/**
  ETFAna project, Anyang Normal University && IMP-CAS
  \class ETFMUSIC
  \brief MUlti-Sampling Ionization Chamber
  \author SUN Yazhou, asia.rabbit@163.com
  \since 2024-01-05
  \date 2024-01-05 last modified
  \attention
  changelog
  <table>
  <tr>  <th>Date         <th>Author      <th>Description                   </tr>
  <tr>  <td>2024-01-05   <td>Asia Sun    <td>file created                  </tr>
  </table>

  \copyright Copyright (c) 2021-2024 Anyang Normal U. && IMP-CAS with LGPLv3 LICENSE
*/

#include <iostream>
#include <TTree.h>
#include "ETFRun.h"
#include "ETFMUSIC.h"
#include "ETFAmpCh.h"
#include "ETFDetectorManager.h"
#include "ETFMsg.h"

using std::cout;
using std::endl;

ETFMUSIC::ETFMUSIC(const char *name) : ETFDetector(name){
  // allocate channel id
  fNUnit = fChIdConfig.size();
  fdE = new short[fNUnit];
  for(int i = 0; i < fNUnit; i++){
    const int chid = fChIdConfig[i].as<int>();
    const int uid = fDetId + (i<<8);
    SetChMap(chid, uid);
    fdE[i] = -1.;
  } // end for over units
} // end ctor

ETFMUSIC::~ETFMUSIC(){
  delete fdE;
} // end dtor

void ETFMUSIC::Initialize(){
  ETFDetector::Initialize();
  for(int i = fNUnit; i--;) fdE[i] = -1.;
  fdE_ = -1.;
} // end member function Initialize

// identify the channel by its uid
void ETFMUSIC::Assign(const ETFRawChannel *ch, unsigned uid){
  const ETFAmpCh *ach = dynamic_cast<const ETFAmpCh *>(ch);
  if(ach && ach->nv()) fdE[(uid>>8) & 0x1F] = static_cast<short>(ach->value());
  else ETFMsg::Warn("ETFMUSIC", "Assign: not a amplitude ch or it is an empty ach");
  fIsFired = true;
} // end member function Assign

void ETFMUSIC::Register(){
  fTree->Branch(GetName(), &fdE_, Form("%s/D", GetName()));
  string b0 = Form("%sv", GetName()), b1 = Form("%sv[%d]/S", GetName(), fNUnit);
  fTree->Branch(b0.data(), fdE, b1.data());
} // end member function PostInit

// return fdE[i]
short ETFMUSIC::dE(int i) const{
  if(i < 0 || i > fNUnit) return -1.;
  return fdE[i];
} // end member function dE

// finish the processing of all the assigned data
void ETFMUSIC::PostAssign(){
  if(!fIsFired) return;
  short ii = 0, s = 0;
  for(int i = 0; i < fNUnit; i++) if(fdE[i] > 0){
    s += fdE[i];
    ii++;
  } // end for
  fdE_ = s/(ii*1000.);
} // end member function PostAssign

void ETFMUSIC::Print(){
  if(!fIsFired) return;
  ETFDetector::Print();
  cout << "---------------------" << endl;
  for(int i = 0; i < fNUnit; i++) cout << "fdE[" << i << "]: " << fdE[i] << " \t";
  cout << endl << "    Averaged dE: " << fdE_ << endl;
  cout << endl << "---------------------" << endl;
} // end member function Print
